﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MM.Commmon.UI;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using System.Diagnostics;
using DevExpress.XtraNavBar;
using DevExpress.XtraExport;
using MM.Common.Base;
using DevExpress.XtraPrinting;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Export;

namespace MM.Common.Setup
{
    public partial class FrmSetupCommon : FrmFunctionWithTool
    {
        private string codeName;
        protected DataTable dtSetup = new DataTable();
        protected GridView gvSetup;
        private string idName;
        protected string InputColumn = "";
        private string[] keyCols;
        private string[] noCols;
        protected string sqlSetup;

        public FrmSetupCommon()
        {
            InitializeComponent();
            codeName = "";
            idName = "";

        }

        protected virtual bool BeforeSave()
        {
            return true;
        }

        private void Export_Progress(object sender, ProgressEventArgs e)
        {
            if (e.Phase == ExportPhase.Link)
            {
                this.progressBarControl1.Position = e.Position;
                base.Update();
            }
        }

        private void ExportTo(IExportProvider provider)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            base.FindForm().Refresh();
            BaseExportLink link = this.gvSetup.CreateExportLink(provider);
            (link as GridViewExportLink).ExpandAll = false;
            link.Progress += new ProgressEventHandler(this.Export_Progress);
            link.ExportTo(true);
            provider.Dispose();
            link.Progress -= new ProgressEventHandler(this.Export_Progress);
            Cursor.Current = current;
        }

        protected virtual void freshData()
        {
            if (this.getData())
            {
                this.setCellEvent();
            }
            else
            {
                base.Close();
            }
        }

        private void FrmSetupCommon_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ((this.dtSetup.GetChanges() != null) && (XtraMessageBox.Show("还有未保存的修改信息, 是否继续?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel))
            {
                e.Cancel = true;
            }
        }

        protected bool getData()
        {
            this.dtSetup.Rows.Clear();
            if (SystemInfo.DbData.Retrieve(this.sqlSetup, ref this.dtSetup))
            {
                this.gvSetup.GridControl.DataSource = this.dtSetup;
                this.nbiSave.Visible = false;
                return true;
            }
            XtraMessageBox.Show("取数据不成功！\r\n" + SystemInfo.DbData.ErrorMessage, "出错");
            return false;
        }

        private void gvCellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            this.nbiSave.Visible = true;
            if (e.Column.Name == this.InputColumn)
            {
                string source = e.Value.ToString();
                string inputCode = IME.GetInputCode(source, "1");
                this.gvSetup.SetRowCellValue(e.RowHandle, "INPUTCODE1", inputCode);
                inputCode = IME.GetInputCode(source, "2");
                this.gvSetup.SetRowCellValue(e.RowHandle, "INPUTCODE2", inputCode);
            }
        }

        private void gvFocusedColumnChanged(object sender, FocusedColumnChangedEventArgs e)
        {
            object tag = e.FocusedColumn.Tag;
            if ((tag != null) && (tag.ToString() == "ON"))
            {
                this.gvSetup.GridControl.ImeMode = ImeMode.On;
            }
            else
            {
                this.gvSetup.GridControl.ImeMode = ImeMode.Off;
            }
        }


        private void nbiDelete_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if ((this.gvSetup.FocusedRowHandle >= 0) && (XtraMessageBox.Show("是否真的删除?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK))
            {
                this.gvSetup.DeleteRow(this.gvSetup.FocusedRowHandle);
                this.gvSetup.Focus();
                this.nbiSave.Visible = true;
            }
        }

        private void nbiExcel_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            this.ucPanel1.Visible = true;
            string fileName = this.ShowSaveFileDialog("Excel 文件", "Excel 文件|*.xls");
            if (fileName != "")
            {
                //this.ExportTo(new ExportXlsProvider(fileName));
                this.OpenFile(fileName);
            }
            this.ucPanel1.Visible = false;
        }

        private void nbiExit_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            base.Close();
        }

        private void nbiFresh_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            bool flag = true;
            if ((this.dtSetup.GetChanges() != null) && (XtraMessageBox.Show("还有未保存的修改信息, 是否继续?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel))
            {
                flag = false;
            }
            if (flag)
            {
                this.freshData();
            }
        }

        private void nbiHTML_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            string fileName = this.ShowSaveFileDialog("HTML 文件", "HTML 文件|*.html");
            if (fileName != "")
            {
                this.ExportTo(new ExportHtmlProvider(fileName));
                this.OpenFile(fileName);
            }
        }

        private void nbiNew_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            DataRow row = this.dtSetup.NewRow();
            if (this.codeName.Length > 0)
            {
                if (this.dtSetup.Columns[this.codeName].DataType.ToString() == "System.String")
                {
                    try
                    {
                        row[this.codeName] = "1";
                        for (int i = this.dtSetup.Rows.Count - 1; i >= 0; i--)
                        {
                            if (this.dtSetup.Rows[i].RowState != DataRowState.Deleted)
                            {
                                string str = this.dtSetup.Rows[i][this.codeName].ToString();
                                string str2 = (Convert.ToInt32(str) + 1).ToString();
                                while (str2.Length < str.Length)
                                {
                                    str2 = "0" + str2;
                                }
                                row[this.codeName] = str2;
                                goto Label_0192;
                            }
                        }
                    }
                    catch
                    {
                        row[this.codeName] = "";
                    }
                }
                else
                {
                    row[this.codeName] = 1;
                    for (int j = this.dtSetup.Rows.Count - 1; j >= 0; j--)
                    {
                        if (this.dtSetup.Rows[j].RowState != DataRowState.Deleted)
                        {
                            row[this.codeName] = Convert.ToInt32(this.dtSetup.Rows[j][this.codeName]) + 1;
                            break;
                        }
                    }
                }
            }
        Label_0192:
            this.dtSetup.Rows.Add(row);
            this.gvSetup.ClearSorting();
            this.gvSetup.FocusedRowHandle = this.gvSetup.RowCount - 1;
            this.gvSetup.Focus();
            this.nbiSave.Visible = true;
        }

        private void nbiPrint_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            //if (PrintHelper.IsPrintingAvailable)
            //{
            //    PrintHelper.ShowPreview(this.gvSetup.GridControl);
            //}
            //else
            //{
            //    XtraMessageBox.Show("打印库文件未找到！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            //}
            //Cursor.Current = Cursors.Default;
        }

        private void nbiSave_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if (this.idName.Length > 0)
            {
                this.setId();
            }
            this.BeforeSave();
            if (SystemInfo.DbData.Update(this.dtSetup, this.keyCols, this.noCols))
            {
                this.nbiSave.Visible = false;
                XtraMessageBox.Show("更新成功！", "提示");
            }
            else
            {
                XtraMessageBox.Show("更新不成功！原因：" + SystemInfo.DbData.ErrorMessage, "出错", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        private void nbiTXT_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            string fileName = this.ShowSaveFileDialog("文本文件", "文本文件|*.txt");
            if (fileName != "")
            {
                this.ExportTo(new ExportTxtProvider(fileName));
                this.OpenFile(fileName);
            }
        }

        private void nbiXML_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            string fileName = this.ShowSaveFileDialog("XML 文件", "XML 文件|*.xml");
            if (fileName != "")
            {
                this.ExportTo(new ExportXmlProvider(fileName));
                this.OpenFile(fileName);
            }
        }

        private void OpenFile(string fileName)
        {
            if (XtraMessageBox.Show("是否打开文件?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    new Process { StartInfo = { FileName = fileName, Verb = "Open", WindowStyle = ProcessWindowStyle.Normal } }.Start();
                }
                catch
                {
                    XtraMessageBox.Show(this, "不能找到打开该文件的系统。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
            this.progressBarControl1.Position = 0;
        }

        protected void setCellEvent()
        {
            if (this.gvSetup != null)
            {
                this.gvSetup.CellValueChanged += new CellValueChangedEventHandler(this.gvCellValueChanged);
                this.gvSetup.FocusedColumnChanged += new FocusedColumnChangedEventHandler(this.gvFocusedColumnChanged);
            }
        }

        private void setId()
        {
            int num = 0;
            for (int i = 0; i < this.dtSetup.Rows.Count; i++)
            {
                if ((this.dtSetup.Rows[i].RowState != DataRowState.Added) && (this.dtSetup.Rows[i].RowState != DataRowState.Deleted))
                {
                    int num3 = Convert.ToInt16(this.dtSetup.Rows[i][this.idName]);
                    if (num3 > num)
                    {
                        num = num3;
                    }
                }
            }
            for (int j = 0; j < this.dtSetup.Rows.Count; j++)
            {
                if (this.dtSetup.Rows[j].RowState == DataRowState.Added)
                {
                    this.dtSetup.Rows[j][this.idName] = ++num;
                }
            }
        }

        protected void setSql(string selsql, string tablename, string[] keycols, string[] nocols, string codename, string idname)
        {
            this.sqlSetup = selsql;
            this.dtSetup.TableName = tablename;
            this.keyCols = keycols;
            this.noCols = nocols;
            this.codeName = codename;
            this.idName = idname;
        }

        private string ShowSaveFileDialog(string title, string filter)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            string tableName = this.dtSetup.TableName;
            int startIndex = tableName.LastIndexOf(".") + 1;
            if (startIndex > 0)
            {
                tableName = tableName.Substring(startIndex, tableName.Length - startIndex);
            }
            dialog.Title = "导出到：" + title;
            dialog.FileName = tableName;
            dialog.Filter = filter;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                return dialog.FileName;
            }
            return "";
        }

        private void ucPanel1_Resize(object sender, EventArgs e)
        {
            this.progressBarControl1.Width = this.ucPanel1.Width;
        }
    }
}
